/**
 * 对接文档
 * https://help.aliyun.com/zh/oss/use-cases/obtain-signature-information-from-the-server-and-upload-data-to-oss?spm=a2c4g.11186623.0.i7
 * */
const OSS = require('ali-oss')
const dayjs = require('dayjs')

/** RAM */
// AccessKey ID     -     LTAI5tCiogm5FVZvg9C6DLAC
// AccessKey Secret -     koJlkvIKaZ0K0wFQ8oIKvv3f1n3lRK
// 角色 ARN         -     acs:ram::1189767726130909:role/ramossuser

const Config = {
  accessKeyId: 'LTAI5tCiogm5FVZvg9C6DLAC',
  accessKeySecret: 'koJlkvIKaZ0K0wFQ8oIKvv3f1n3lRK',
  roleArn: 'acs:ram::1189767726130909:role/ramossuser',
  region: 'oss-cn-shanghai',
  bucket: 'pulmonary',
}
const ExpireSeconds = 3000
const FileSizeLimit = 1048576000 // 字节，~ 100mb

async function getSTSToken() {
  const { accessKeyId, accessKeySecret, roleArn } = Config
  const sts = new OSS.STS({ accessKeyId, accessKeySecret });
  const {
    credentials: { AccessKeyId, AccessKeySecret, SecurityToken },
  } = await sts.assumeRole(roleArn, '', ExpireSeconds, 'sessiontest');
  return {
    accessKeyId: AccessKeyId,
    accessKeySecret: AccessKeySecret,
    stsToken: SecurityToken
  }
}

async function getOSSSign() {
  // const dir = "user-dirs/";
  const policy = {
    expiration: dayjs().add(ExpireSeconds, 'second').toISOString(), // 请求有效期。
    conditions: [
      ["content-length-range", 0, FileSizeLimit], // 设置上传文件的大小限制。
      // ["starts-with", "$key", dir], // 限制文件只能上传到user-dirs目录下。
      { bucket: Config.bucket }, // 限制文件只能上传至指定Bucket。
    ],
  };
  /* 使用stsToken的方式上传。*/
  const { accessKeyId, accessKeySecret, stsToken } = await getSTSToken()
  const client = new OSS({
    accessKeyId,
    accessKeySecret,
    stsToken,
    refreshSTSToken: getSTSToken,
    refreshSTSTokenInterval: ExpireSeconds * 100,
  });

  // 计算签名。
  const formData = await client.calculatePostSignature(policy);

  // 返回参数。
  const params = {
    expire: dayjs().unix().toString(),
    policy: formData.policy,
    signature: formData.Signature,
    accessid: formData.OSSAccessKeyId,
    stsToken,
    host: `http://${Config.bucket}.${Config.region}.aliyuncs.com`,
    // dir,
  };

  return params;
}

module.exports.getOSSSign = getOSSSign
